<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Lua在线运行工具</title>
    <meta name="description" content="在线运行Lua脚本">
    <meta name="author" content="chenxuuu">
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/fengari-web.js" type="text/javascript"></script>
    <link rel="stylesheet" href="codemirror-5.49.2/lib/codemirror.css" />
    <script src="codemirror-5.49.2/lib/codemirror.js"></script>
    <script src="codemirror-5.49.2/mode/lua/lua.js"></script>
    <link rel="stylesheet" href="codemirror-5.49.2/theme/mdn-like.css" />
    <style>
        .CodeMirror-line {
            font-family: Consolas, 'Microsoft Yahei' !important;
        }
    </style>
</head>

<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <h3>
                    Lua在线运行工具
                </h3>
                <div class="alert alert-warning alert-dismissable">
                    <h4>注意</h4>
                    每次运行时，Lua虚拟机并不会刷新，前一次的变量都会被保存。如果需要彻底重新运行，请点击刷新按钮：
                    <button class="btn btn-primary btn-outline-primary" onclick="newLuaState()">
                        刷新虚拟机
                    </button><br>
                    <span id="saveText">当前代码会自动保存在浏览器缓存，下次打开自动加载。</span><br>
                    Lua运行环境为Lua 5.3。集成moonscript，可直接require("moonscript")
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6">
                <h3>
                    待运行代码：
                </h3>
                <textarea class="form-control" id="code" name="code"></textarea>
                <button class="btn btn-primary btn-block btn-outline-primary" onclick="getResult()">
                    运行
                </button>
            </div>
            <div class="col-md-6">
                <h3>
                    运行结果：
                </h3>
                <textarea class="form-control" id="output" readonly="true"
                    style="position: relative;width: 100%;height: 370px;">虚拟机初始化中，请稍后。。。</textarea>
                <button class="btn btn-primary btn-block btn-outline-primary" id="d_clip_button" data-clipboard-text="">
                    分享这段代码
                </button>
            </div>
        </div>
    </div>
    <div style="text-align: center;"><a href="https://github.com/chenxuuu/lua-online" target="_blank">GitHub 源码</a>
    <div id="qrcode"></div>
    </div>
    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/luaTask.js"></script>
    <script>

        var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
            mode: "text/x-lua", //实现lua代码高亮
            lineNumbers: true,  //显示行号
            theme: "mdn-like",  //设置主题
            indentUnit: 4,
            indentWithTabs: true,
            matchBrackets: true,
        });
        editor.setSize("100%", 370);

        var pageurl = window.location.href;
        if (pageurl.indexOf("?") >= 0)
            pageurl = pageurl.substring(0, pageurl.indexOf("?"));
        var shareButton = document.getElementById("d_clip_button");
        editor.on("change", function () {
            if (location.search == "")
                localStorage.setItem("code", editor.getValue());
            shareButton.setAttribute("data-clipboard-text", pageurl + "?" + escape(editor.getValue()) + "%0d%0a");
        });

        if (location.search != ""){
            var scode = location.search.substring(1);
            if (scode.indexOf("&") >= 0)
                scode = scode.substring(0,scode.indexOf("&"))
            editor.setValue(unescape(scode));
            $("#saveText").text("当前代码为分享代码，不会自动保存，关闭浏览器后就会消失");
        }
        else if (localStorage.getItem("code") != null) {
            editor.setValue(localStorage.getItem("code"));
        }

        function luaPrint(s) {
            var textarea = $("#output").append(s + "\n");
            textarea.scrollTop(textarea[0].scrollHeight - textarea.height());
        }

var lua

function getResult() {
    var code = editor.getValue();
    $("#output").text("");
    try {
        var r = lua.doString(code);
        if(!r.success) {
            luaPrint("虚拟机报错：");
            luaPrint(r.error);
        }
    }
    catch (err) {
        luaPrint("js环境报错：");
        luaPrint(err);
    }
}

function newLuaState() {
    if(typeof(lua) != "undefined")
        lua.clean();
    lua = new LuaTask();
    lua.doString(`
js = require "js"
--重写print函数
function print(...)
    local out = {}
    for i=1,select('#', ...) do
        table.insert(out,tostring(select(i, ...)))
    end
    js.global:luaPrint(table.concat(out,"\t"))
end
package.path = "./lua/?.lua"
require("head")`);
    $("#output").text("");
    luaPrint("虚拟机初始化完毕");
}
newLuaState();


    </script>
    <script type="text/javascript" src="js/clipboard.min.js"></script>
    <script>
        var btn = document.getElementById('d_clip_button');
        var clipboard = new ClipboardJS(btn);

        clipboard.on('success', function (e) {
            alert("复制成功~粘贴即可分享代码链接\r\n下方的二维码也可用来分享");
            qrcode.makeCode(shareButton.getAttribute("data-clipboard-text"));
        });
        clipboard.on('error', function (e) {
            alert("复制失败了呢，你还是手动复制吧");
        });
    </script>
    <script type="text/javascript" src="js/qrcode.js"></script>
    <script>
        var qrcode = new QRCode(document.getElementById("qrcode"), {
            text: "https://chenxuuu.gitee.io/lua-online/",
            width: 256,
            height: 256,
            colorDark : "#000000",
            colorLight : "#ffffff",
            correctLevel : QRCode.CorrectLevel.L
        });
        qrcode.clear(); // clear the code.
    </script>
    <script>
        var _hmt = _hmt || [];
        (function() {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?2e02fb796d5ae8812686e6270227de97";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        })();
    </script>
</body>

</html>
